﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.RecurringJobs
{
    /// <summary>
    /// ClearRedis Job
    /// </summary>
    public class RedisJob : BpmReportPlatformRecurringJob, IRedisJob
    {
        private readonly string cookie;
        private readonly string url;
        private readonly string logPath;
        private ILogger _logger;
        public RedisJob(IConfiguration configuration,  ILogger logger)
        {
            url = configuration["RedisSetting:Url"];
            cookie = configuration["RedisSetting:Cookie"];
            logPath = configuration["RedisSetting:LogPath"];
            _logger = logger;
        }

        /// <summary>
        /// 清除Dashboard调用记录
        /// </summary>
        public void ClearRedisLog()
        {
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Add("cookie", cookie);
                var response = client.GetAsync($"{url}").Result;
                if (response.IsSuccessStatusCode)
                {
                    string content = response.Content.ReadAsStringAsync().Result;
                    var result = JsonConvert.DeserializeObject<RedisListDto>(content);

                    if (result == null)
                    {
                        return;
                    }

                    var names = result.Data.Select(x => x.Name).ToList();
                    names.ForEach(x =>
                    {
                        Console.WriteLine($"clean ==>{x}, time is:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                        var httpClient = new HttpClient();
                        httpClient.DefaultRequestHeaders.Add("cookie", cookie);
                        var data = client.PostAsync(new Uri($"{url}/{x}/clean"), null);
                    });
                    Console.WriteLine($"clean end, time is:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                }
 
            }
            catch (Exception ex)
            {
 
            }
        }

        
    }
}
